package com.tutucms.service.admin.common;

import com.tutucms.common.security.MD5Util;
import com.tutucms.common.util.CharUtil;
import com.tutucms.repo.entity.User;
import com.tutucms.service.auth.UserContextCache;
import com.tutucms.service.common.SessionHolder;
import com.tutucms.service.model.consts.Const;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;

/**
 * Created by wangxudong on 2020/4/9.
 */
@Slf4j
@Component
public class UserContext {

    @Value("${app.token.timeout:4320}")
    private Long tokenTimeout;

    @Autowired
    private UserContextCache userContextCache;

    // 获取当前请求用户
    public User getUser() {
        HttpServletRequest request = SessionHolder.getRequest();
        if (request == null) {

            return null;
        }
        Object object = request.getAttribute(Const.CURRENT_ATTRIBUTE_KEY);
        if (object != null) {

            return (User) object;
        }

        return null;
    }

    // 移除当前登录的用户
    public void removeUser() {
        User user = getUser();
        if (user != null) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("Authorization");
            userContextCache.delete(Const.USER_TOKEN_PREFIX + token);
            userContextCache.delete(Const.USER_KEY_PREFIX + user.getId());
        }
    }

    public String login(User user) {
        String token = generateToken(user);
        userContextCache.set(Const.USER_TOKEN_PREFIX + token, user.getId(), tokenTimeout);
        userContextCache.set(Const.USER_KEY_PREFIX + user.getId(), user, tokenTimeout);

        return token;
    }


    public void updateLoginUser(User user) {

        userContextCache.set(Const.USER_KEY_PREFIX + user.getId(), user, tokenTimeout);
    }

    private String generateToken(User user) {
        String token = "TUtu";
        token += (System.currentTimeMillis() + "").substring(0, 5);
        token += CharUtil.getRanString(64, false);
        token += (System.currentTimeMillis() + "").substring(0, 5);
        token = MD5Util.getMD5String(token);
        return Base64.getEncoder().encodeToString((token == null ? "" : token).getBytes());
    }

}